package com.asiainfo.demo.service;

import com.asiainfo.demo.dao.DaoFactory;
import com.asiainfo.demo.dao.idao.iBind;
import com.asiainfo.demo.dao.idao.iCard;
import com.asiainfo.demo.dao.idao.iMember;
import com.asiainfo.demo.dao.roles.Bind;
import com.asiainfo.demo.dao.roles.Card;
import com.asiainfo.demo.dao.roles.Member;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MemberManage {
    private static iMember memDao = DaoFactory.getMemInstance();
    private static iBind bindDao = DaoFactory.getBindInstance();
    private static iCard cardDao = DaoFactory.getCardInstance();

    public static boolean addMember(Member member) {
        boolean flag = false;
        try {
            flag = memDao.insertMember(member);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    public static boolean bindCard(Member member, Card card, int times) {
        boolean hasMember = false;
        boolean bindResult = false;

        try {
            ArrayList<Member> foundMems = memDao.findMemberByName(member.getMemName());
            for(Member foundMem : foundMems){
                if(foundMem.getMemID() == member.getMemID()){
                    Bind bind = new Bind(member.getMemID(), card.getCardID(), times);
                    bind.setSignTime(new Date());
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.YEAR, card.getCardType() == (byte) 1 ? 1 : 3);
                    bind.setLastTime(calendar.getTime());

                    bindResult = cardDao.insertCard(card) && bindDao.insertBind(bind);
                    hasMember = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(!hasMember){
            System.out.println("Member Not Found. Bind Card Failed.");
        }

        return bindResult;
    }

    public static Member findMemberByName(String memName){
        ArrayList<Member> foundMems;
        Member foundMem = null;

        try {
            foundMems = memDao.findMemberByName(memName);
            if (foundMems.size() > 1){
                System.out.println("DUPLICATED NAMES!");
            }
            else if (foundMems.size() == 1){
                foundMem = foundMems.get(0);
            }
            else {
                System.out.println("NOT FOUND!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return foundMem;
    }
}
